package pkg

import (
	"github.com/golang-jwt/jwt/v4"
	"strconv"
	"time"
)

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体
const JwtSecretKey = "2209ayk"
const JwtSeconds = 86400

func GetJwtToken(payload string) (string, error) {
	iat := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + JwtSeconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(JwtSecretKey))
}

func ParseJwtToken(tokenString string) (payload int64, err error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(JwtSecretKey), nil
	})
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return int64(claims[strconv.FormatInt(payload, 10)].(float64)), nil
	} else {
		return 0, nil
	}
}
